package org.teamh.connection.json.handler;

import org.teamh.connection.json.event.JsonEventObject;
import org.teamh.game.Start;
import org.teamh.gui.Event;
import org.teamh.logic.datamodel.Cell;
import org.teamh.logic.datamodel.DatamodelManager;
import org.teamh.logic.datamodel.Tower;

public class TowerHandler extends JsonMasterHandler {

	public TowerHandler(Start start, DatamodelManager manager) {
		super(start, manager);
	}

	public boolean handleMsg(JsonEventObject json) {
		
		if (json.getSource().startsWith("Tower@")) {
			if (json.getProperty().equals("cell")) {
				if(json.getNewValue() != null) {
					Tower tower = manager.getTower(json.getSource());
					if(tower == null) {
						tower = new Tower(json.getSource(), start);
						manager.addTower(tower);
					}
					Cell cell = manager.getCell(json.getNewValue());
					if(cell != null) {
						tower.setCell(cell);
					}
				}
				
				return true;
			} else if (json.getProperty().equals("building")) {
				manager.getTower(json.getSource()).setBuilding(Boolean.parseBoolean(json.getNewValue()));
				return true;
			} else if (json.getProperty().equals("buildProgress")) {
				Tower t = manager.getTower(json.getSource());
				if(t != null) {
					t.setBuildProgress(Double.parseDouble(json.getNewValue()));
				}
				return true;
			} else if (json.getProperty().equals("type")) {
				manager.getTower(json.getSource()).setType(json.getNewValue());
				return true;
			} else if (json.getProperty().equals("level")) {
				manager.getTower(json.getSource()).setLevel(Integer.parseInt(json.getNewValue()));
				return true;
			} else if (json.getProperty().equals("upgrading")) {
				boolean upgrading =  Boolean.parseBoolean(json.getNewValue());
				manager.getTower(json.getSource()).setUpgrading(upgrading);
				if(upgrading) {
					start.getGui().addEvent(new Event("upgradeTower", json.getSource()));
				}
				return true;
			} else if (json.getProperty().equals("userAssets")) {
				if (json.getNewValue() != null) {
					manager.getTower(json.getSource()).setUserAssets(manager.getUserAssets(json.getNewValue()));
				}		
				return true;
			} else if (json.getProperty().equals("color")) {
				if (json.getNewValue() != null) {
					manager.getTower(json.getSource()).setColor(json.getNewValue());
				}		
				return true;
			} else if (json.getProperty().equals("selling")) {
				manager.getTower(json.getSource()).setSelling(Boolean.parseBoolean(json.getNewValue()));
				return true;
			} else if (json.getProperty().equals("strategy")) {
				manager.getTower(json.getSource()).setStratetgy(json.getNewValue());
				return true;
			}  
			
			return false;
		} else {
			return false;
		}
	}
}
